<?php

namespace app\admin\controller\site;

use app\admin\service\SiteAdminService;
use app\admin\service\SiteGroupService;
use app\site\service\site\SiteConfigService;
use think\Db;
use Throwable;
use app\common\controller\Backend;

/**
 * 站点管理管理
 */
class Site extends Backend
{
    /**
     * Site模型对象
     * @var object
     * @phpstan-var \app\admin\model\site\Site
     */
    protected object $model;

    protected string|array $defaultSortField = 'site_id,desc';

    protected array $withJoinTable = ['siteGroup'];

    protected array|string $preExcludeFields = ['createtime'];

    protected string|array $quickSearchField = ['site_id'];


    /**
     * 关闭站点ID数据限制
     * @var bool
     */
    protected bool $limitSiteId = false;


    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\site\Site();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['siteGroup' => ['group_name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
            'where'  => $where
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $site_group_id = $data['site_group_id'];
            $site_group = (new SiteGroupService())->info(['id' => $site_group_id]);
            if(!$site_group) {
                $this->error('站点套餐不存在');
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);

                $result = (new SiteAdminService())->addAmin(
                    $this->model->site_id,
                    $data['username'],
                    $data['password'],
                    $data['organize_name'],
                    $data['contact_mobile'],
                    $site_group['group_roles'],
                    1
                );

                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }




    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            if($this->site_id != 0){
                $data['site_id'] = $this->site_id;
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                event('siteUpdate', $row);
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);

    }



    /**
     * 初始化配置
     * @return void
     */
    public function initConfig()
    {
        $site_ids = $this->request->post('site_id');
        if(!$site_ids){
            $this->error('参数错误');
        }

        $ret = false;
        $list = $this->model->whereIn('site_id',$site_ids)->select();
        foreach ($list as $item){
            $ret += (new SiteConfigService())->init($item->site_id);
        }

        //if(!$ret) $this->error('初始化配置失败');
        $this->success('初始化配置成功');
    }



}